import "reflect-metadata"
import dotenv from "dotenv"
import { AppDataSource } from "./config/database"
import app from "./app"
import logger from "./utils/logger"
import { paymentStatusService } from './services/PaymentStatusService'

// 加载环境变量
dotenv.config()
process.env.TZ = 'Asia/Shanghai'; // 设置为北京时间
const PORT = process.env.PORT || 3000

process.on('uncaughtException', (err) => {
    console.error('未捕获异常:', err);

    // 可在此处记录日志或发送警报
    logger.error("Error uncaughtException:", err)
});

AppDataSource.initialize()
    .then(() => {
        logger.info("Data Source has been initialized!")

        // 启动支付状态同步服务
        paymentStatusService.start()
        logger.info("支付状态同步服务已启动")

        app.listen(PORT, () => {
            logger.info(`Server is running on port ${PORT}`)
        })
    })
    .catch((err) => {
        logger.error("Error during Data Source initialization:", err)
    })

// 处理应用退出
process.on('SIGINT', () => {
    logger.info('应用正在关闭...')
    paymentStatusService.stop()
    AppDataSource.destroy().then(() => {
        logger.info('数据库连接已关闭')
        process.exit(0)
    })
})